//
//  SurpriseShopDetailVC.swift
//  XiaoJingMallSwift
//
//  Created by beisheng03 on 2017/8/14.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage


protocol SurprisDetailBottomDelegate : NSObjectProtocol {
    
    func rightBuyBtnDidTap(str : String)
    
}

class SurpriseShopDetailVC: BaseViewController {
    
    var odId = "-999"
    
    var hasmore = "-999"
    
    var page = -999
    
    var dataModel : SurpriseShopDetModel?
    
    lazy var bottomView : SurpriseDetailBottomView = {
        
        let temp = Bundle.main.loadNibNamed(self.StringFromClass(classType: SurpriseDetailBottomView.self), owner: nil, options: nil)?.first as! SurpriseDetailBottomView
        
        temp.isHidden = true
        
        
        temp.frame = CGRect(x: 0, y: KScreenH - 49, width: KScreenW, height: 49)

        temp.delegate = self
        
        self.view.addSubview(temp)
        
        
        return temp
        
    }()

    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.title = "鲸喜购"

        plainTableView.tableFooterView = UIView()
        
        plainTableView.backgroundColor = UIColor.viewBgGrey()
        
        plainTableView.separatorStyle = .none
        
        plainTableView.register(BaseTableViewCell.self, forCellReuseIdentifier: BaseTableViewCell.identifer())
        plainTableView.register(SurpiseDetailSetionHeard.self, forHeaderFooterViewReuseIdentifier: SurpiseDetailSetionHeard.identifer())

        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetailTopCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetailTopCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetailOneStyleCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetailOneStyleCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetaiTwoStyleCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetaiTwoStyleCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetailThreeStyleCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetailThreeStyleCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetailMiddleCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetailMiddleCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: SurpriseShopDetailListCell.self), bundle: nil), forCellReuseIdentifier: SurpriseShopDetailListCell.identifer())
        plainTableView.register(UINib(nibName: StringFromClass(classType: LuckyNumsDisplayCell.self), bundle: nil), forCellReuseIdentifier: LuckyNumsDisplayCell.identifer())
        
        plainTableView.rowHeight = UITableViewAutomaticDimension
        
        plainTableView.estimatedRowHeight = 100
        
        plainTableView.separatorStyle = .none
        
        weak var weakSelf = self
        
        plainTableView.mj_header =  ZMRefreshHeader.init {
            
            weakSelf!.loadData()
            
        }
        
        plainTableView.mj_header.beginRefreshing()
        
        plainTableView.mj_footer = ZMRefreshFooter.init{
            
            weakSelf!.loadMoreData()
            
        }
        

        
    }
    
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

  
}



extension SurpriseShopDetailVC:SurprisDetailBottomDelegate {

    func rightBuyBtnDidTap(str: String) {
        
        let temp = SurpriseShopOrderVC()
        
        let shopStr = self.dataModel!.od_id + "|" + str
        
        if str == self.dataModel!.od_count {
            temp.allRemain = "1"
        }
        
        QL1(str)
        
        QL1(self.dataModel!.od_count)
        
        QL1(temp.allRemain)
        
        QL1(shopStr)
        
        temp.shopInfoStr = shopStr
        
        
        navigationController?.pushViewController(temp, animated: true)
    }



}


// MARK:- 数据加载
extension  SurpriseShopDetailVC{
    func loadData(){
        
        page = 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["od_id"] = odId as AnyObject
        
        QL1(odId)
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=detail", parameters: parmeter) {[weak self] (responseObject, error)  in
            
            
            if error == nil {
                
                if responseObject == nil {
                    self?.surpriseTable.mj_header.endRefreshing()
                    return
                }
                
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                self?.dataModel = SurpriseShopDetModel(dic: responseObject!["datas"] as! [String : AnyObject])
                
                
                self!.plainTableView.mj_footer.resetNoMoreData()
                
                
                self?.cachePictures()
                
                
            }else{
                
                self!.plainTableView.mj_header.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
            
        }
        
        

        
    }
    
    
    
    
    func cachePictures(){
        
        
        guard let url = URL(string: dataModel!.goods_image) else {
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
                
            }
            
            let temp = dataModel?.od_state ?? "0"
            
            
            if temp == "1"{
                
                bottomView.isHidden = false
            }
            
            if temp == "2"{
                
                bottomView.isHidden = true
                
            }
            
            if temp == "3"{
                
                bottomView.isHidden = true
                
            }
            

            
            self.plainTableView.mj_header.endRefreshing()
            
            
            self.plainTableView.reloadData()
            
            
            return
            
        }
        
        
        
        
        let grop = DispatchGroup()
        
        grop.enter()
        
        SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
            
            grop.leave()
            
        })
        
        
        
        
        grop.notify(queue: DispatchQueue.main) {
            
            
            if self.hasmore == "0" {
                
                self.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                
                
            }
            
            let temp = self.dataModel?.od_state ?? "0"
            
            
            if temp == "1"{
                
                self.bottomView.isHidden = false
            }
            
            if temp == "2"{
                
                self.bottomView.isHidden = true
                
            }
            
            if temp == "3"{
                
                self.bottomView.isHidden = true
                
            }
            

            
            
            
            self.plainTableView.mj_header.endRefreshing()
            
            
            self.plainTableView.reloadData()
            
            
            
        }
        
        
        
        
    }

    
    
    func loadMoreData(){
        
        page += 1
        
        var parmeter  = [String : AnyObject]()
        
        parmeter["curpage"] = "\(page)" as AnyObject
        
        parmeter["od_id"] = odId as AnyObject
        
        
        
        NetworkTools.shared.sendRequest(method: .GET_METHOD, pathStr: "mobile/index.php?c=one_dollar&a=detail", parameters: parmeter) {[weak self] (responseObject, error)  in
            
            
            if error == nil {
                
                if responseObject == nil {
                    self?.surpriseTable.mj_footer.endRefreshing()
                    return
                }
                
                
                self?.hasmore = responseObject!["hasmore"] as! String
                
                
                for dic in responseObject!["datas"]!["join_list"] as! [[String : AnyObject]]{
                    
                    self?.dataModel?.join_list.append(SurpriseShopJoinListModel(dic: dic))
                    
                    
                }
                
                
                
                if self?.hasmore == "0" {
                    
                    self!.plainTableView.mj_footer.endRefreshingWithNoMoreData()
                    
                    
                }else{
                    
                    self!.plainTableView.mj_footer.endRefreshing()
                    
                }
                
                
                self?.plainTableView.reloadData()
                
            }else{
                
                self!.plainTableView.mj_footer.endRefreshing()
                
                SVProgressHUD.showError(withStatus: error?.domain)
                
                
            }
            
            
            
        }
        
        
    }

    
}




// MARK:- table代理
extension  SurpriseShopDetailVC{
    
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        
        if dataModel == nil {
            return 0
        }
        
        return 2
    }
    
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
       
        
        if dataModel == nil {
            return 0
        }
        

        if section == 0 {
            
            if dataModel?.lucky_nums != nil {
                return 4
            } else {
                return 3
            }
            
        } else {
            
            return dataModel?.join_list.count ?? 0
        }
    }
    
    

    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//        LuckyNumsDisplayCell   BaseTableViewCell
        var tableCell : UITableViewCell? = nil
        
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                
                let tempCell : SurpriseShopDetailTopCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailTopCell.identifer()) as! SurpriseShopDetailTopCell
                
                tempCell.model = dataModel
                
                tableCell = tempCell
                
            }else if indexPath.row == 1 {
                
                let temp = dataModel?.od_state ?? "0"
                
                switch temp {
                case "1":
                    let tempCell : SurpriseShopDetailOneStyleCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailOneStyleCell.identifer()) as! SurpriseShopDetailOneStyleCell
                    
                    tempCell.model = dataModel
                    
                    tableCell = tempCell
                    
                case "2":
                    let tempCell : SurpriseShopDetaiTwoStyleCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetaiTwoStyleCell.identifer()) as! SurpriseShopDetaiTwoStyleCell
                    
                    tempCell.model = dataModel
                    
                    tableCell = tempCell
                    
                case "3":
                    
                    let tempCell : SurpriseShopDetailThreeStyleCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailThreeStyleCell.identifer()) as! SurpriseShopDetailThreeStyleCell
                    
                    tempCell.model = dataModel
                    
                    tableCell = tempCell
                    
                default:
                    let tempCell : BaseTableViewCell =  tableView.dequeueReusableCell(withIdentifier: BaseTableViewCell.identifer()) as! BaseTableViewCell
                    
                    tableCell = tempCell
                }
                
                
                
                
                
            }else if indexPath.row == 2 {
                
                
                if dataModel?.lucky_nums != nil {
                    
                    let tempCell : LuckyNumsDisplayCell =  tableView.dequeueReusableCell(withIdentifier: LuckyNumsDisplayCell.identifer()) as! LuckyNumsDisplayCell
                    
                    tempCell.textStr = dataModel?.lucky_nums
                    
                    tableCell = tempCell
                    

                } else {
                    
                    let tempCell : SurpriseShopDetailMiddleCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailMiddleCell.identifer()) as! SurpriseShopDetailMiddleCell
                    
                    tempCell.model = dataModel
                
                    tableCell = tempCell
                    

                }
                
                
            }else{
                
                let tempCell : SurpriseShopDetailMiddleCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailMiddleCell.identifer()) as! SurpriseShopDetailMiddleCell
                
                tempCell.model = dataModel

                
                tableCell = tempCell
                
                
            }
            
        } else {
            
            let tempCell : SurpriseShopDetailListCell =  tableView.dequeueReusableCell(withIdentifier: SurpriseShopDetailListCell.identifer()) as! SurpriseShopDetailListCell
            
            tempCell.model = dataModel?.join_list[indexPath.row]
            
            tableCell = tempCell
            
            
        }
        
        
        
        return tableCell!
        
    }
    
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        
        QL1("-------")
    }
    
    

    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        if section == 0 {
            
            return 0
            
        } else {
            
            return 36
        }
    }
    
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            
            return nil
            
        } else {
            
            let temp = tableView.dequeueReusableHeaderFooterView(withIdentifier: SurpiseDetailSetionHeard.identifer()) as! SurpiseDetailSetionHeard
            
            temp.rightStr = dataModel!.od_addtime + " 开始"
            
            return temp
        }
        
    }

    
}
